package com.intretech.umsin.auth.controller;

import com.intretech.umsin.auth.feign.SystemFeign;
import com.intretech.umsin.auth.model.LoginBody;
import com.intretech.umsin.auth.model.SmsLoginBody;
import com.intretech.umsin.auth.service.SysLoginService;
import com.intretech.umsin.common.web.ApiResult;
import com.intretech.umsin.security.satoken.config.annotation.Anonymous;
import com.intretech.umsin.system.param.SysDictItemParam;
import com.intretech.umsin.system.vo.SysDictItemVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.function.Function;

/**
 * @version V1.0
 * @ClassName: AuthController
 * @Description: 功能描述 认证鉴权控制器
 * @author: 李启联
 * @date: 2022-8-10 9:38
 * @Copyright: Copyright (c) 2022
 */

@Validated
@Api(value = "认证鉴权控制器", tags = {"认证鉴权管理"})
//@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SystemFeign systemFeign;

    @PostMapping("/list")
    @ApiOperation(value = "查询系统字典详情信息对象列表", notes = "查询返回系统字典详情信息对象列表")
    public ApiResult<List<SysDictItemVo>> queryForList(@RequestBody SysDictItemParam params){
        return systemFeign.querySysDictItemForList(params);
    }

    @Anonymous
    @ApiOperation("登录方法")
    @PostMapping("/login")
    public ApiResult<String> login(@Validated @RequestBody LoginBody form) {

        // 用户登录
        Function<LoginBody,String> fun = p -> sysLoginService.login(p.getAccount(), p.getPassword());
       return ApiResult.responseFor(fun,form);
    }

    /**
     * 短信登录
     *
     * @param smsLoginBody 登录信息
     * @return 结果
     */
    @ApiOperation("短信登录")
    @PostMapping("/smsLogin")
    public ApiResult<String> smsLogin(@Validated @RequestBody SmsLoginBody smsLoginBody) {
        // 生成令牌
        Function<SmsLoginBody,String> fun = p -> sysLoginService.smsLogin(p.getPhonenumber(), p.getSmsCode());
        return ApiResult.responseFor(fun,smsLoginBody);
    }

    /**
     * 小程序登录
     *
     * @param appletCode 小程序code
     * @return 结果
     */
    @ApiOperation("小程序登录")
    @PostMapping("/appletLogin")
    public ApiResult<String> appletLogin(@NotBlank(message = "appletCode.not.blank") String appletCode) {
        Function<String,String> fun = p -> sysLoginService.appletLogin(p);
        return ApiResult.responseFor(fun,appletCode);
    }

    @ApiOperation("登出方法")
    @DeleteMapping("/logout")
    public ApiResult<Void> logout() {
        try {
            sysLoginService.logout();
            return ApiResult.succeedResponse();
        }catch (Exception e) {
            return ApiResult.failedResponse();
        }
    }



}